<template>
  <el-dialog
      v-model="computedDialogVisible"
      title="修改用户"
      width="30%"
  >
    <el-form label-width="120px">
      <el-form-item label="昵称">
        <el-input v-model="formData.nickName"></el-input>
      </el-form-item>
      <el-form-item label="用户头像">
        <image-uploader :limit="1" ref="uploader"></image-uploader>
      </el-form-item>
      <el-form-item label="用户角色">
        <role-selector v-model:role-ids="roleIds"></role-selector>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="computedDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import {computed, ref, watch} from "vue";
import {User} from "@/typings";
import {ElMessage} from "element-plus";
import {getUser, updateUser} from "@/api/system/user";
import Uploader from "@/components/uploader/uploader.vue";
import RoleSelector from "@/components/system/role/role-selector.vue";
import {updateUserRole} from "@/api/system/role";
import ImageUploader from "@/components/uploader/image-uploader.vue";

const props = defineProps({dialogVisible: {type: Boolean, default: false}, id: {type: String, required: true}})
const emits = defineEmits(['update:dialog-visible', 'submit'])
let formData = ref<User>({} as User)
let uploader = ref<InstanceType<typeof ImageUploader>>()
let roleIds = ref<string[]>([])
watch(() => props.id, (value, oldValue) => {
  getUser(value).then((res: User) => {
    if (uploader.value) {
      uploader.value.setSingleFileUrl(res.avatar)
    }
    formData.value = res
    roleIds.value = res.roles.map(value => value.roleId)
  })
})
let computedDialogVisible = computed({
  get: () => {
    return props.dialogVisible
  },
  set: (value) => {
    emits('update:dialog-visible', value)
  }
})
const handleConfirm = () => {
  if (uploader.value) {
    let uploadFiles = uploader.value.getUploadFiles();
    formData.value.avatar = uploadFiles[0].path
  }
  updateUser(formData.value).then(res => {
    if (res == true) {
      ElMessage.success({message: '修改成功'})
      computedDialogVisible.value = false
      emits('submit')
    }
  })
  updateUserRole(formData.value.userId, roleIds.value).then(res => {
    roleIds.value = []
  })
}
</script>

<style lang="scss" scoped>
.upload-section {
  .cover {
    margin-top: 20px;
  }
}
</style>